<template>
  <el-card shadow="never" v-if="showStatus" class="mainCard">
    <div class="state flex flex-row w-[100%] gap-10 items-center">
      <Icon icon="ep:arrow-left" class="ml-1 !font-800 cursor-pointer" size="36" @click="resetStatus" />
      <el-card class="w-[15%] h-25 cursor-pointer" v-for="(item, index) in cardData"
        @click="filterStatusData(item.type)" :key="index"
        :class="{ 'ml-auto': index === 0, 'mr-12': index === cardData.length - 1 }">
        <div class="stateBox flex flex-row justify-evenly items-center">
          <span class="iconfont" :class="`icon-${item.type}`"></span>
          <div class="info ">
            <span class="num block w-full text-3xl text-center">{{ item.count }}</span>
            <span class="desc block w-full text-center font-serif  ">{{ item.status }}</span>
          </div>
        </div>
      </el-card>
    </div>
    <div class=" flex items-center mx-8 hborder hidden   " :class="judgeAdmin() ? 'flex-col gap-3' : ''">
      <el-button class="" size="large" type="primary"
        @click="() => openForm('create', undefined, true)">客户注册提报</el-button>
      <!--  v-hasPermi="['quote:customer:admin-create']" -->
      <el-button v-hasPermi="['quote:customer:admin-create']" class="" size="large" type="warning"
        @click="() => openForm('admin-create', undefined, true)">管理员创建客户</el-button>
    </div>
  </el-card>

  <ContentWrap class="mt-6">
    <!-- 搜索工作栏 -->
    <el-form class="-mb-15px  mt-4 flex" :model="queryParams" ref="queryFormRef" :inline="true" label-width="100px">
      <div class="titleBar flex flex-row items-center w-[250px] mb-5">
        <svg xmlns="http://www.w3.org/2000/svg" width="1.5em" height="1.5em" viewBox="0 0 24 24">
          <path fill="#aaa"
            d="M4.808 9.616q-.343 0-.576-.233T4 8.808V6.923q0-.343.232-.575t.576-.232h1.884q.343 0 .576.232t.232.575v1.885q0 .343-.232.575t-.576.233zm4.077 0q-.344 0-.576-.233q-.232-.232-.232-.575V6.923q0-.343.232-.575t.575-.232h10.308q.344 0 .576.232t.232.575v1.885q0 .343-.232.575t-.576.233zm0 3.923q-.344 0-.576-.233q-.232-.232-.232-.575V11q0-.343.232-.575q.232-.233.576-.233h10.307q.344 0 .576.232T20 11v1.73q0 .344-.232.576t-.576.233zm0 4.077q-.344 0-.576-.233q-.232-.232-.232-.575v-1.885q0-.343.232-.576t.575-.232h10.308q.344 0 .576.232q.232.233.232.576v1.885q0 .343-.232.575t-.576.233zm-4.077 0q-.344 0-.576-.233T4 16.808v-1.885q0-.343.232-.576t.576-.232h1.884q.343 0 .576.232q.232.233.232.576v1.885q0 .343-.232.575t-.576.233zm0-4.077q-.344 0-.576-.233T4 12.731V11q0-.343.232-.575t.576-.233h1.884q.343 0 .576.232T7.5 11v1.73q0 .344-.232.576t-.576.233z" />
        </svg>
        <span class="text-16px">已注册客户列表</span>
      </div>
      <el-form-item v-if="!showStatus" class="!ml-auto " label="" prop="date">
        <el-button class="" type="primary" @click="() => showStatus = true">注册记录</el-button>
      </el-form-item>
      <el-form-item :class="{ '!ml-auto': showStatus }" label="" prop="date">
        <el-date-picker size="default" v-model="queryParams.createTime" value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange" start-placeholder="开始日期" end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]" class="!w-220px" />
      </el-form-item>
      <el-form-item v-hasPermi="['quote:customer:audit']" label="" prop="name">
        <el-select @change="changeListByOwner" v-model="queryParams.ownerId" collapse-tags style="width: 139px"
          placeholder="请选择负责人" size="default">
          <el-option v-for="(dict, index) in opt" :label="dict.label" :value="dict.value" :key="index" />
        </el-select>
      </el-form-item>
      <el-form-item class="" label="" prop="search">
        <el-input v-model="queryParams.search" placeholder="请输入您想要搜索的内容" clearable @keyup.enter="handleQuery"
          class="!w-240px " />
      </el-form-item>

      <el-form-item class="">
        <el-button @click="handleQuery">
          <Icon icon="ep:search" class="mr-5px" /> 搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon icon="ep:refresh" class="mr-5px" /> 重置
        </el-button>
        <!-- <el-button type="primary" plain @click="openForm('create')" v-hasPermi="['quote:customer:create']">
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button> -->
        <el-button type="success" plain @click="handleExport" :loading="exportLoading"
          v-hasPermi="['quote:customer:export']">
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>

    <el-table class="mt-9" :header-cell-style="{ backgroundColor: '#f2f2f2', fontWeight: 700, color: '#909399' }"
      v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <!-- <el-table-column label="序号" align="left" width="60" prop="id" /> -->
      <el-table-column label="客户名称" align="left" width="240" prop="name" />
      <el-table-column label="客户地址" width="300" align="left" prop="detailAddress" />
      <el-table-column label="联络人" align="left" prop="contactName" />
      <el-table-column label="联系电话" align="left" prop="mobile" width="180" />
      <el-table-column label="E-mail" width="220" align="left" prop="email" />
      <el-table-column label="成为负责人的时间" width="160" :formatter="handleDate" align="left" prop="createTime" />
      <el-table-column label="负责人" align="left" prop="ownerUserName" />
      <el-table-column label="状态" align="left" prop="status">
        <template #default="scope">
          {{ getStrDictOptions(DICT_TYPE.QUOTATION_STATUS).filter(item => item.value == scope.row.status)[0]?.label }}
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" align="center" width="270">
        <template #default="scope">
          <el-button link type="primary" v-if="scope.row.status == '0'" @click="openForm('audit', scope.row, false)">
            审核
          </el-button>
          <el-button link v-if="scope.row.status != '2'" type="primary" @click="openForm('assign', scope.row, true)"
            v-hasPermi="['quote:customer:changeOwner']">
            再分配
          </el-button>
          <!-- 目前只有status ==0  也就是未通过的客户可以修改 -->
          <el-button link type="primary" v-if="scope.row.status == 0 || scope.row.status == 1"
            v-hasPermi="['quote:customer:update']" @click="openForm('update', scope.row, false)">
            编辑
          </el-button>
          <el-button link type="primary" @click="openForm('detail', scope.row, false)">
            详情
          </el-button>
          <el-button link type="primary" v-hasPermi="['quote:customer:delete']" @click="handleDelete(scope.row.id)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination class="myPagination" layout=" total, prev, pager, next, jumper," v-show="total > 0" :total="total"
      v-model:limit="queryParams.pageSize" v-model:page="queryParams.pageNo" @pagination="getList" />
  </ContentWrap>


  <!-- 表单弹窗：添加/修改 -->
  <CustomerForm ref="formRef" @success="getList" />
</template>

<script setup lang="ts">
import { formatDate } from '@/utils/formatTime'
import download from '@/utils/download'
import { CustomerApi, CustomerVO } from '@/api/quote/customer'
import CustomerForm from './CustomerForm.vue'
import '@/assets/iconfont/iconfont.css'
import { DICT_TYPE, getStrDictOptions } from '@/utils/dict'
import { CACHE_KEY, useCache } from '@/hooks/web/useCache'

enum STATUS {
  "yitongguo" = '1',
  "yibohui" = '2',
  "daishenhe" = '0',

}

/** 客户 列表 */
defineOptions({ name: 'Customer' })

const showStatus = ref(false) // 显示状态
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const formRef = ref()
const cardData = ref([
  {
    type: 'yitongguo',
    realKey: 'audit',
    count: 0,
    status: '已通过',
  },
  {
    type: 'yibohui',
    realKey: 'reject',
    count: 0,
    status: '已驳回',
  },
  {
    type: 'daishenhe',
    count: 0,
    realKey: 'processing',
    status: '待审核',
  },
])
let opt = ref([] as any)
const loading = ref(true) // 列表的加载中
const list = ref<CustomerVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  name: undefined,
  detailAddress: undefined,
  ownerUserId: undefined,
  ownerTime: [],
  mobile: undefined,
  telephone: undefined,
  qq: undefined,
  wechat: undefined,
  email: undefined,
  areaId: undefined,
  remark: undefined,
  status: undefined,
  createTime: [],
  search: undefined,
  ownerId: ''
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中


const resetStatus = () => {
  showStatus.value = false
  getList()
}

const handleDate = (row: any) => {
  return formatDate(row.createTime)
}
const judgeAdmin = () => {
  const { wsCache } = useCache()
  const permissions = wsCache.get(CACHE_KEY.USER).permissions
  const all_permission = '*:*:*'
  const hasPermissions = permissions.some((permission: string) => {
    return permission == all_permission || permission.includes('quote:quotation:audit')
  })
  return hasPermissions
}

const filterStatusData = async (status: string) => {
  if (status) {
    await getList(STATUS[status]);
  }
}

// 初始化card数据

const getCardData = async () => {
  const res = await CustomerApi.getAllStatus();
  let keys = Object.keys(res);
  keys.forEach((item: any, index: number) => {
    cardData.value[index].count = res[item]
  })
}
const changeListByOwner = (val) => {
  queryParams.ownerId = val
  getList()

}

/** 查询列表 */
const getList = async (status: any = 1) => {
  loading.value = true
  if (typeof status != 'object') {
    queryParams.status = status
  } else {
    Object.assign(queryParams, status)
  }

  try {
    getCardData()
    list.value = []
    const data = await CustomerApi.getCustomerPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList({ status: '' })
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  queryParams.createTime = []
  queryParams.ownerId = ''
  handleQuery()
}

/** 添加/修改操作 */

const openForm = (type: string, id?: number, flag) => {
  formRef.value.open(type, id, flag)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CustomerApi.deleteCustomer(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch { }
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await CustomerApi.exportCustomer(queryParams)
    download.excel(data, '客户.xlsx')
  } catch {
  } finally {
    exportLoading.value = false
  }
}


const getAllOwner = async () => {
  const res = await CustomerApi.getOwner();
  if (res) {
    opt.value = [];
    res.list.forEach((item: any) => {
      opt.value.push({ label: item.nickname, value: item.id })
    })
  }
}

/** 初始化 **/
onMounted(() => {
  getCardData()
  getList()
  judgeAdmin() && getAllOwner()
})
</script>

<style lang="scss" scoped>
:deep(.el-table__row--striped .el-table__cell) {
  background: #f2f2f2 !important;
}

:deep(.el-table__header) {
  .cell {
    font-weight: 900 !important;
    color: #101010 !important;
  }
}

:deep(.el-table__row) {
  .cell {
    font-family: Roboto, BlinkMacSystemFont, "Helvetica Neue", Arial, "Microsoft Yahei", "WenQuanYi Micro Hei", "Pingfang SC", sans-serif;
    font-weight: 400 !important;
    color: #101010 !important;
  }
}


.mainCard {
  &> :deep(.el-card__body) {
    display: flex;
  }
}

.hborder {
  position: relative;

  &::before {
    position: absolute;
    content: "";
    display: block;
    width: 2px;
    height: 100%;
    left: -40px;
    background-color: rgba(160, 159, 158, 0.4);
  }
}
</style>
